package userserv

import (
	"codedef"
	"config"
	"encoding/json"
	"log"
	"net/http"
)

func updateForm(w http.ResponseWriter, r *http.Request) {
	type SetSwitchAction struct {
		Cid string `json:"cid"`
	}

	var uniqueId string
	uniqueId = r.Header.Get("uniqueId")

	log.Printf("setSwitch, uniqueId:%s\n", uniqueId)

	message := make([]byte, r.ContentLength)
	n, _ := r.Body.Read(message)
	if n != int(r.ContentLength) {
		log.Println("setSwitch failed, can't read request body")
		replyError(w, codedef.ERR_REQUEST_INVALID_PARAM)
		return
	}

	//log.Println(string(message))

	var action SetSwitchAction
	err := json.Unmarshal(message, &action)
	if err != nil {
		log.Println("setSwitch failed, json decode failed:", err)
		replyError(w, codedef.ERR_DECODE)
		return
	}

	errCode := checkDevCtrlAction(action.Cid, uniqueId)
	if errCode != codedef.ERR_SUCCEED {
		log.Println("setSwitch failed, check task error:", err)
		replyError(w, codedef.ERR_OPRATION_FAILD)
		return
	}

	type UpgradeRequest struct {
		URI        string `json:"uri"`
		URL        string `json:"url"`
		NewVersion string `json:"newVersion"`
	}

	var ur = &UpgradeRequest{}
	ur.URI = "/upgrade"
	ur.NewVersion = config.LatestFirmVersion
	ur.URL = config.FirmDownloadUrl
	c := getOnlineControllerById(action.Cid)
	if c == nil {
		log.Printf("controller %s not exist", action.Cid)
		return
	}

	log.Printf("update %s firm", action.Cid)

	controller := getOnlineControllerById(action.Cid)
	if controller == nil {
		log.Println("syncPlan2Device failed, no online controller for:", action.Cid)
		replyError(w, codedef.ERR_CONTROLLER_OFFLINE)
		return
	}

	if controller.isBusy() {
		log.Println("syncPlan2Device failed, controller is busy:", action.Cid)
		replyError(w, codedef.ERR_CONTROLLER_BUSY)
		return
	}

	if wait := syn2Device(*controller, ur); wait != nil {
		//log.Println("start to reply app.", string(wait))

		devMessage, errCode := parserDevReply(wait)
		if 0 != errCode {
			replyError(w, codedef.ERR_OPRATION_FAILD)
		}

		replyBuffer(w, devMessage)
		//go GetRuntimeInfo(w, controller)
	} else {
		log.Println("save setSwitch failed, error:", err)
		replyError(w, codedef.ERR_CONTROLLER_NO_RESPONSE)
		return
	}
}

func init() {
	myMux.muxHandlers.HandleFunc("/updateForm", updateForm)
}
